import { defineComponent, ref, watch } from "vue";
import { area, country, rural } from "@/config/areas";

export default defineComponent({
  emits: ['change'],
  setup(props, { expose, emit }) {
    // 打开            
    const open = (e: { mode: string, field: string, address: string[], index: number }) => {
      address_cascader.value.mode = e.mode;
      address_cascader.value.field = e.field;
      address_cascader.value.address = e.address;
      address_cascader.value.index = e.index || 0;
      address_cascader.value.is_show = true;
    }
    //弹窗关闭回调
    const closed = () => {
      address_cascader.value.mode = '';
      address_cascader.value.field = '';
      address_cascader.value.address = [];
      address_cascader.value.index = 0;
    }
    //地址级联选择器
    const address_cascader = ref({
      is_show: false,
      mode: '',
      index: 0,
      field: '',
      address: [] as string[],
      options: area.map((x: any) => {
        x.children = Object.entries(country).filter((y: any) => y[0] === x.area_name).map((y:any) => y[1].map((z: any) => {
          z.children = Object.entries(rural).filter((k: any) => k[0] === z.area_name).map(y => y[1])[0];
          return z;
        }))[0];
        return x;
      }),
    })
    // 监听到弹窗被关闭时触发回调
    watch(() => address_cascader.value.is_show, (nv) => {
      if (!nv) {
        closed();
      }
    })
    expose({
      open,
    })
    return () => (
      <nut-cascader
        title="户口所在地选择"
        v-model:visible={address_cascader.value.is_show}
        v-model={address_cascader.value.address}
        options={address_cascader.value.options}
        onChange={(e: any) => {
          emit('change', {
            mode: address_cascader.value.mode,
            field: address_cascader.value.field,
            index: address_cascader.value.index,
            address: e,
          })
        }}
        text-key="area_name"
        value-key="area_name"
        children-key="children"
      ></nut-cascader>
    )
  }
})